
import 'package:dali_ng_pera/net/dnp_net_config.dart';
import 'package:dio/dio.dart';
import 'dnp_http_result.dart';

class DnpNetManager {

  static final DnpNetManager _instance = DnpNetManager._internal();
  factory DnpNetManager() => _instance;
  DnpNetManager._internal() {
    _init();
  }

  late Dio _dio;

  void _init() {
    _dio = Dio(BaseOptions(
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
      sendTimeout: const Duration(seconds: 30),
      responseType: ResponseType.json,
    ));

    // 添加拦截器
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        options.headers['Content-Type'] = 'application/json';
        return handler.next(options);
      },
      onResponse: (response, handler) {
        return handler.next(response);
      },
      onError: (DioException e, handler) {
        return handler.next(e);
      },
    ));
  }

  // GET 请求
  Future<DnpHttpResult> get(
      String path, {
        Map<String, dynamic>? queryParameters,
        Map<String, dynamic>? headers,
        Options? options,
      }) async {
    try {
      final response = await _dio.get(
        DnpNetConfig().globalPath(path),
        queryParameters: queryParameters,
        options: options?.copyWith(headers: headers) ?? Options(headers: headers),
      );

      dynamic resultData = response.data;

      if (resultData is Map<String,dynamic>) {

        dynamic iesous = resultData["iesous"];
        dynamic kurios = resultData["kurios"];
        dynamic close = resultData["close"];

        return DnpHttpResult(
          success: iesous == "0" || iesous == "-1",
          close:close,
          kurios: kurios,
          iesous:iesous,
        );
      }else {
        return DnpHttpResult(
          success: false,
          kurios: 'Network Error',
        );
      }
    } on DioException catch (e) {
      return _handleError(e);
    } catch (e) {
      return DnpHttpResult(
        success: false,
        kurios: 'Unknown Error: $e',
      );
    }
  }

  // POST 请求
  Future<DnpHttpResult> post(
      String path, {
        dynamic data,
        Map<String, dynamic>? headers,
        Options? options,
      }) async {
    try {
      final response = await _dio.post(
        DnpNetConfig().globalPath(path),
        data: data,
        queryParameters: {},
        options: options?.copyWith(headers: headers) ?? Options(headers: headers),
      );

      dynamic resultData = response.data;

      if (resultData is Map<String,dynamic>) {

        dynamic iesous = resultData["iesous"];
        dynamic kurios = resultData["kurios"];
        dynamic close = resultData["close"];

        return DnpHttpResult(
          success: iesous == "0" || iesous == "-1",
          close:close,
          kurios: kurios,
          iesous:iesous,
        );
      }else {
        return DnpHttpResult(
          success: false,
          kurios: 'Network Error',
        );
      }
    } on DioException catch (e) {
      return _handleError(e);
    } catch (e) {
      return DnpHttpResult(
        success: false,
        kurios: 'Unknown Error: $e',
      );
    }
  }

  // 上传图片
  Future<DnpHttpResult> uploadImage<T>(
      String path, {
        List<int>? imageBytes,
        Map<String, dynamic> queryParameters = const {},
      }) async {
    try {

      Options options = Options(method: "POST");

      final form = FormData.fromMap(queryParameters);

      if (imageBytes != null) {
        form.files.add(MapEntry(
            "turnedIn",
            MultipartFile.fromBytes(imageBytes, filename: 'image.png')
        ));
      }

      final response = await _dio.request(
        DnpNetConfig().globalPath(path),
        data:form,
        queryParameters: {},
        options: options,
      );

      dynamic resultData = response.data;

      if (resultData is Map<String,dynamic>) {

        dynamic iesous = resultData["iesous"];
        dynamic kurios = resultData["kurios"];
        dynamic close = resultData["close"];

        return DnpHttpResult(
          success: true,
          close:close,
          kurios: kurios,
          iesous:iesous,
        );
      }else {
        return DnpHttpResult(
          success: false,
          kurios: 'Network Error',
        );
      }
    } on DioException catch (e) {
      return _handleError(e);
    } catch (e) {
      return DnpHttpResult(
        success: false,
        kurios: 'Unknown Error: $e',
      );
    }
  }

  // 错误处理
  DnpHttpResult _handleError(DioException e) {
    String errorMessage = 'Network Error';

    return DnpHttpResult(
      success: false,
      kurios: errorMessage,
      iesous: "-1",
    );
  }

  // 取消请求
  void cancelRequests({CancelToken? token}) {
    token?.cancel('请求取消');
  }

}